package model

import (
	"OJCenter/global"
	"OJCenter/idl"
	"encoding/json"
	"github.com/nsqio/go-nsq"
	"strconv"
)

func (m *Model) SubProblem(sub *idl.Submission) error {
	err := m.S.InsertSubmissionInfo(sub)
	if err != nil {
		return err
	}
	return nil
}

func (m *Model) GetSubmissionInContest(uid int64, cid int64, pid int64) (*[]idl.Submission, error) {
	pids, err := m.S.GetSubmissionCodeInfoFromCache(uid, cid, pid)
	if err != nil {
		data, err := m.S.GetSubmissionInfoWithDataByUCPId(uid, cid, pid)
		if err != nil {
			return nil, err
		}
		return data, err
	}
	return pids, nil
}

func (m *Model) GetSubmission(uid int64, pid int64) (*[]idl.Submission, error) {
	return m.S.GetSubmissionInfosFromDataByUPId(uid, pid)
}

func (m *Model) ConsumeJMessage(message *nsq.Message) error {
	var Jr idl.JResult
	var err error
	var CMap map[string]interface{}

	err = json.Unmarshal(message.Body, &Jr)
	if err != nil {
		global.Logger.Errorf("messge body unmarshal failed")
		return err
	}
	//TODO:res存入数据库
	CMap["res_info"] = message.Body
	CMap["sid"], err = strconv.Atoi(Jr.Sid)
	if err != nil {
		global.Logger.Errorf("Jid:%v,handle JResult failed,err:%v", message.ID, err)
		return err
	}
	if len(Jr.Passed) == 0 {
		CMap["result"] = "Fail"
	}
	if len(Jr.Passed) != 0 {
		CMap["result"] = "AK"
	}
	if len(Jr.UnPassed) == 0 {
		CMap["result"] = "AC"
	}
	err = m.S.UpdateSubmissionInfo(&CMap)
	if err != nil {
		global.Logger.Errorf("update sub by nsq failed,err:%v", err)
		return err
	}
	return nil
}
